import Dexie, {Table} from "dexie";
import {
  IHealthArchiveCloud,
  ITerminalB04_53,
  ITerminalBase,
} from "@/model/IA00_04";
import dayjs from "dayjs";
import {
  IBiochemicalCloud,
  IBiochemistry,
  IBiochemistryCloud, IBloodPressCloud,
  IBusResult,
  IBusViewCloud, Ihw700Cloud,
} from "@/model/TerminalType";
import {IQRCodeInfo} from "@/model/IQRCodeInfo";
import {ElMessage} from "element-plus";

type IUrinalysis = {};

export class AppDatabase extends Dexie {
  bloodPressure!: Table<Partial<IBloodPressCloud>>;
  agedTcm!: Table<Partial<ITerminalB04_53>>;
  hw700!: Table<Partial<Ihw700Cloud>>;
  urinalysis!: Table<IUrinalysis>;
  healthCheck!: Table<Partial<IHealthArchiveCloud>>;
  biochemical!: Table<Partial<IBiochemicalCloud>>;
  busView!: Table<Partial<IBusViewCloud>>;
  busResult!: Table<IBusResult>;
  biochemistry!: Table<IBiochemistryCloud>;

  constructor() {
    super("ContactsDatabase");
    this.version(15).stores({
      bloodPressure: "++id,qr_code_id,measureTime,synchronous",
      agedTcm: "++id,qr_code_id,measureTime,synchronous",
      hw700: "++id,qr_code_id,measureTime,synchronous",
      urinalysis: "++id,qr_code_id,measureTime,synchronous",
      healthCheck: "++id,qr_code_id,measureTime,synchronous",
      biochemical: "++id,qr_code_id,measureTime,synchronous",
      busView: "++id,qr_code_id,measureTime,synchronous",
      busResult: "++id",
      biochemistry: "++id,qr_code_id,measureTime,synchronous",
    });
  }
}

export const db = new AppDatabase();
export const pageLocalRequest = async (
  db: Table,
  searchItem: {
    measureTime: Array<string>;
    name: string;
    pageNum: number;
    pageSize: number;
  }
) => {
  // const data = await db.where()
  let collection;
  const filter = (item) => {
    if (!searchItem.name) {
      return true;
    }
    if (item.userName && item.userName.indexOf(searchItem.name) !== -1) {
      return true;
    }
    if (item.cardId && item.cardId.indexOf(searchItem.name) !== -1) {
      return true;
    }
    return false;
  };
  if (searchItem.measureTime && searchItem.name) {
    collection = db
      .where("measureTime")
      .between(
        dayjs(searchItem.measureTime[0]).valueOf(),
        dayjs(searchItem.measureTime[1]).valueOf()
      )
      .filter(filter);
  } else if (searchItem.measureTime) {
    collection = db
      .where("measureTime")
      .between(
        dayjs(searchItem.measureTime[0]).valueOf(),
        dayjs(searchItem.measureTime[1]).valueOf()
      );
  } else if (searchItem.name) {
    collection = db.filter(filter);
  } else {
    collection = db;
  }
  const data = await collection
    .offset((searchItem.pageNum - 1) * searchItem.pageSize)
    .limit(searchItem.pageSize)
    .reverse()
    .toArray();
  const total = await collection.count();
  console.log(data, total);
  return {
    data: data,
    total: total,
  };
};
export const asyncLocalRequest = async (db: Table) => {
  const data = await db.where("synchronous").equals(0).toArray();
  return data;
};

export class DbService<T extends Partial<ITerminalBase>> {
  db: Table<T>;

  constructor(db: Table<T>) {
    this.db = db;
  }

  async deleteRows(ids: Array<string>) {
    return this.db.bulkDelete(ids);
  }

  async saveCard(data: T, qrCodeInfo: Partial<IQRCodeInfo>) {
    return new Promise(async (resolve, reject) => {
      const oneRow = await this.db.where({qr_code_id: qrCodeInfo.id}).toArray();
      if (oneRow.length > 0) {
        await this.deleteRows(oneRow.map((item) => item.id as string));
      }
      const row: T = {...data};
      row.qr_code_id = qrCodeInfo.id;
      row.userName = qrCodeInfo.username;
      row.sex = qrCodeInfo.sex;
      row.synchronous = 0;
      row.cardId = qrCodeInfo.idno;
      row.measureTime = Date.now();
      try {
        delete row.id
      } catch (e) {
      }
      await this.db.add(row);
      resolve({
        code: 0,
        message: "保存成功！",
      });
    }).catch((err) => {
      ElMessage.error("保存失败！");
    });
  }
}
